<template>
  <div class="hot-products">
    <div class="section-header">
      <div class="header-content">
        <h3 class="section-title">热门商品</h3>
        <span class="section-subtitle">大家都在看</span>
      </div>
      <el-button text type="primary" @click="goToProducts" class="more-btn">
        <span>查看更多</span>
        <el-icon><ArrowRight /></el-icon>
      </el-button>
    </div>

    <div v-loading="loading" class="products-grid">
      <div v-for="(product, index) in products" :key="product.id" class="product-card" @click="goToProductDetail(product.id)">
        <div class="product-image">
          <el-image :src="getProductImage(product)" fit="cover" class="image">
            <template #error>
              <div class="image-error">
                <el-icon size="32">
                  <Picture />
                </el-icon>
                <span>暂无图片</span>
              </div>
            </template>
          </el-image>
          <div class="product-overlay">
            <div class="overlay-content">
              <el-button type="primary" size="small" class="view-btn">
                查看详情
              </el-button>
            </div>
          </div>
          <div v-if="product.isBargain" class="bargain-tag">
            <el-tag type="warning" size="small" effect="dark">可砍价</el-tag>
          </div>
          <div v-if="product.oldLevel" class="old-level-tag">
            <el-tag type="info" size="small" effect="dark">{{ getOldLevelText(product.oldLevel) }}</el-tag>
          </div>
          <div class="product-rank" v-if="index < 3">
            <div class="rank-badge rank-{{ index + 1 }}">
              {{ index + 1 }}
            </div>
          </div>
        </div>

        <div class="product-info">
          <div class="product-title text-clamp-2">{{ product.name }}</div>
          <div class="product-owner">
            <span class="owner-label">卖家：</span>
            <span class="owner-name">{{ maskUserName(userInfoMap.get(product.userId)?.userName || userInfoMap.get(product.userId)?.userAccount || '未知用户') }}</span>
          </div>
          <div class="product-price">
            <span class="current-price">¥{{ product.price }}</span>
            <span class="price-unit">起</span>
          </div>
          <div class="product-meta">
            <span class="inventory">
              <el-icon size="12"><Box /></el-icon>
              库存 {{ product.inventory }}
            </span>
            <span class="old-level">
              <el-icon size="12"><View /></el-icon>
              {{ getOldLevelText(product.oldLevel) }}
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && products.length === 0" class="empty-state">
      <div class="empty-icon">
        <el-icon size="64"><Goods /></el-icon>
      </div>
      <h4 class="empty-title">暂无热门商品</h4>
      <p class="empty-desc">快来发布第一个商品吧</p>
      <el-button type="primary" @click="goToPublish" v-if="userStore.isLoggedIn">
        立即发布
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

import { Product } from '@/types'
import { useUserStore } from '@/stores/user'
import request from '@/utils/request'
import { getOldLevelText, maskUserName } from '@/utils/product'
import { ArrowRight, Picture, Box, View, Goods } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)

// 使用正确的 Product 类型
const products = ref<Product[]>([])
const userInfoMap = ref<Map<number, any>>(new Map())

// 处理商品图片
const getProductImage = (product: Product) => {
  if (product.coverList && product.coverList.length > 0) {
    return product.coverList
  }
  return '/placeholder.svg'
}

// 跳转到商品详情
const goToProductDetail = (productId: number) => {
  router.push(`/product/${productId}`)
}

// 获取用户信息
const fetchUserInfo = async (userId: number) => {
  if (userInfoMap.value.has(userId)) {
    return userInfoMap.value.get(userId)
  }
  
  try {
    const userInfo = await userStore.getUserById(userId)
    if (userInfo) {
      userInfoMap.value.set(userId, userInfo)
    }
    return userInfo
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

// 跳转到商品列表
const goToProducts = () => {
  router.push('/products')
}

// 跳转到发布页面
const goToPublish = () => {
  router.push('/publish')
}

// 加载热门商品数据
const loadHotProducts = async () => {
  loading.value = true
  try {
    console.log('尝试加载热门商品数据')
    const response = await request.get('/product/list', {
      params: {
        pageNum: 1,
        pageSize: 6,
        isBargain: 1
      }
    })

    console.log('热门商品API响应:', response)

    if (response && response.data && response.data.records) {
      products.value = response.data.records
      console.log('成功加载热门商品数据:', products.value.length, '个商品')
      
      // 为每个商品获取用户信息
      for (const product of products.value) {
        if (product.userId) {
          await fetchUserInfo(product.userId)
        }
      }
    } else {
      throw new Error('热门商品数据格式错误')
    }
  } catch (error) {
    console.error('加载热门商品失败:', error)
    // 如果API失败，使用默认数据
    products.value = []
    console.log('使用默认热门商品数据')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadHotProducts()
})
</script>

<style scoped>
.hot-products {
  background: #fff;
  padding: 40px;
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 107, 53, 0.1);
  position: relative;
  overflow: hidden;
}

.hot-products::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #ff6b35 0%, #f7931e 100%);
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 35px;
  position: relative;
}

.header-content {
  flex: 1;
}

.section-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  color: #2c3e50;
  font-weight: 700;
  letter-spacing: -0.5px;
  position: relative;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -6px;
  left: 0;
  width: 35px;
  height: 3px;
  background: linear-gradient(90deg, #ff6b35, #f7931e);
  border-radius: 2px;
}

.section-subtitle {
  color: #7f8c8d;
  font-size: 15px;
  font-weight: 400;
  letter-spacing: -0.1px;
}

.more-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #ff6b35;
  font-weight: 500;
  font-size: 15px;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
  background: rgba(255, 107, 53, 0.1);
}

.more-btn:hover {
  background: rgba(255, 107, 53, 0.15);
  transform: translateX(4px);
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.product-card {
  border-radius: 16px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid #f0f0f0;
  background: #fff;
  position: relative;
}

.product-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 20px 40px rgba(255, 107, 53, 0.15);
  border-color: #ff6b35;
}

.product-image {
  position: relative;
  height: 280px;
  overflow: hidden;
}

.image {
  width: 100%;
  height: 100%;
  transition: transform 0.4s ease;
}

.product-card:hover .image {
  transform: scale(1.05);
}

.image-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  color: #adb5bd;
  font-size: 14px;
  gap: 8px;
}

.product-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: all 0.3s ease;
}

.product-card:hover .product-overlay {
  opacity: 1;
}

.overlay-content {
  transform: translateY(20px);
  transition: transform 0.3s ease;
}

.product-card:hover .overlay-content {
  transform: translateY(0);
}

.view-btn {
  background: rgba(255, 255, 255, 0.9);
  color: #ff6b35;
  border: none;
  font-weight: 600;
  padding: 10px 20px;
  border-radius: 25px;
  backdrop-filter: blur(10px);
}

.view-btn:hover {
  background: #ff6b35;
  color: white;
  transform: scale(1.05);
}

.bargain-tag {
  position: absolute;
  top: 12px;
  right: 12px;
  z-index: 2;
}

.old-level-tag {
  position: absolute;
  bottom: 12px;
  left: 12px;
  z-index: 2;
}

.product-rank {
  position: absolute;
  top: 12px;
  left: 12px;
  z-index: 2;
}

.rank-badge {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 14px;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.rank-1 {
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
}

.rank-2 {
  background: linear-gradient(135deg, #c0c0c0 0%, #e5e5e5 100%);
}

.rank-3 {
  background: linear-gradient(135deg, #cd7f32 0%, #daa520 100%);
}

.product-info {
  padding: 20px;
}

.product-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 10px;
  line-height: 1.4;
  min-height: 44px;
}

.product-owner {
  margin-bottom: 12px;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 4px;
}

.owner-label {
  color: #999;
}

.owner-name {
  color: #4facfe;
  font-weight: 500;
}

.product-price {
  margin-bottom: 12px;
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.current-price {
  font-size: 24px;
  font-weight: 700;
  color: #ff6b35;
  line-height: 1;
}

.price-unit {
  font-size: 14px;
  color: #999;
  font-weight: 400;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  color: #7f8c8d;
}

.inventory, .old-level {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #7f8c8d;
}

.empty-icon {
  margin-bottom: 20px;
  color: #cbd5e0;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 14px;
  margin-bottom: 24px;
  color: #7f8c8d;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .hot-products {
    padding: 30px 25px;
    border-radius: 16px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .section-title {
    font-size: 24px;
  }

  .more-btn {
    align-self: flex-end;
  }

  .products-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
  }

  .product-card {
    border-radius: 12px;
  }

  .product-image {
    height: 200px;
  }

  .product-info {
    padding: 16px;
  }

  .product-title {
    font-size: 15px;
    min-height: 40px;
  }

  .current-price {
    font-size: 20px;
  }
}

@media (max-width: 480px) {
  .hot-products {
    padding: 25px 20px;
    border-radius: 12px;
  }

  .section-title {
    font-size: 20px;
  }

  .products-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .product-card {
    border-radius: 12px;
  }

  .product-image {
    height: 220px;
  }

  .product-info {
    padding: 18px;
  }

  .product-title {
    font-size: 16px;
    min-height: 44px;
  }

  .current-price {
    font-size: 22px;
  }

  .product-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }
}
</style>